package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.ProductDao;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public List<ProductModel> findAll() {
        String sql = "select p.*,c.name cuisine_name from product p,cuisine c where\n" +
                "p.cuisine_id=c.id";
        return setData(sql);
    }

    @Override
    public int add(ProductModel productModel) {
        String sql = "insert into product" +
                "(name,normal_price,price,content," +
                "is_show,is_recommend,img_href," +
                "cuisine_id,create_time) values " +
                "('" + productModel.getName() + "'," +
                "" + productModel.getNormalPrice() + "," +
                "" + productModel.getPrice() + "," +
                "'" + productModel.getContent() + "'," +
                "" + productModel.getIsShow() + "," +
                "" + productModel.getIsRecommend() + "," +
                "'" + productModel.getImgHref() + "'," +
                "" + productModel.getCuisineId() + "," +
                "now())";
        return JDBC.excute(sql);
    }

    @Override
    public ProductModel findById(Integer id) {
        String sql = "select p.*,c.name cuisine_name from product p,cuisine c where\n" +
                "p.cuisine_id=c.id";
        sql += " and p.id=" + id;
        List<ProductModel> list = setData(sql);
        return list.size() > 0 ? list.get(0) : null;
    }

    private List<ProductModel> setData(String sql) {
        ResultSet resultSet = JDBC.query(sql);
        List<ProductModel> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                ProductModel model = new ProductModel();
                model.setId(resultSet.getInt("id"));
                model.setName(resultSet.getString("name"));
                model.setNormalPrice(resultSet.getFloat("normal_price"));
                model.setPrice(resultSet.getFloat("price"));
                model.setContent(resultSet.getString("content"));
                model.setImgHref(resultSet.getString("img_href"));
                model.setEnable(resultSet.getInt("enable"));
                model.setCuisineName(resultSet.getString("cuisine_name"));
                model.setCuisineId(resultSet.getInt("cuisine_id"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
